// utils/auth.js
const TOKEN_KEY = 'token'
const USERINFO_KEY = 'userInfo'

export default {
  // 检查登录状态
  checkLogin() {
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync(TOKEN_KEY)
      if (!token) {
        return reject(new Error('未登录'))
      }
      
      uni.request({
        url: ' https://cmcc.byjx.shop/api/login/check',
        header: { 'Authorization': 'Bearer ' + token },
        success: (res) => {
          if (res.data.code === 200) {
            this.setUserInfo(res.data.data.userInfo)
            resolve(res.data.data.userInfo)
          } else {
            this.clearAuth()
            reject(new Error('登录已过期'))
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 静默登录
  silentLogin() {
    return new Promise(async (resolve, reject) => {
      try {
        // 1. 获取微信code
        const [err, loginRes] = await uni.login({ provider: 'weixin' })
        if (err) throw err
        
        // 2. 调用静默登录接口
        const [reqErr, res] = await uni.request({
          url: ' https://cmcc.byjx.shop/api/login',
          method: 'POST',
          data: { code: loginRes.code }
        })
        
        if (reqErr || res.data.code !== 200) {
          throw reqErr || new Error(res.data.msg || '登录失败')
        }
        
        // 3. 保存token和用户信息
        this.setToken(res.data.data.token)
        this.setUserInfo(res.data.data.userInfo)
        
        resolve(res.data.data.userInfo)
      } catch (e) {
        this.clearAuth()
        reject(e)
      }
    })
  },
  
  // 设置token
  setToken(token) {
	  console.log('设置token')
	uni.setStorageSync('token',token)
    uni.setStorageSync(TOKEN_KEY, token)
  },
  
  // 获取token
  getToken() {
    return uni.getStorageSync(TOKEN_KEY)
  },
  
  // 设置用户信息
  setUserInfo(user) {
    uni.setStorageSync(USERINFO_KEY, user)
    uni.$emit('userInfoUpdate', user)
  },
  
  // 获取用户信息
  getUserInfo() {
    return uni.getStorageSync(USERINFO_KEY)
  },
  
  // 清除登录状态
  clearAuth() {
    uni.removeStorageSync(TOKEN_KEY)
    uni.removeStorageSync(USERINFO_KEY)
    uni.$emit('userInfoUpdate', null)
  },
  
  // 跳转到登录页
  navigateToLogin() {
    uni.navigateTo({
      url: '/pages/login/login'
    })
  }
}